/**
 * 项目名：	Rumba Plan
 * 
 * 版权所有(C)，上海海鼎信息工程股份有限公司，2006，所有权利保留。
 * 
 * 文件名：	FVRumbaAdvSys.java
 * 模块说明：	
 * 修改历史：
 * 2006-10-25 - lxm - 创建。
 */
package com.hd123.rumba.cartridge;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Transaction;

import com.hd123.rumba.action.cartridge.ViewCartridgeAdvSys;
import com.hd123.rumba.action.cartridge.ViewCartridgeSystem;
import com.hd123.rumba.action.domain.ViewDomainAdvSys;
import com.hd123.rumba.action.domain.ViewDomainSystem;
import com.hd123.rumba.action.log.ViewActionLog;
import com.hd123.rumba.action.organization.ViewOrganizationAdvSys;
import com.hd123.rumba.action.organization.ViewOrganizationSystem;
import com.hd123.rumba.action.user.ViewRoleAdvSys;
import com.hd123.rumba.action.user.ViewRoleSystem;
import com.hd123.rumba.action.user.ViewUserAdvSys;
import com.hd123.rumba.action.user.ViewUserSystem;
import com.hd123.rumba.cartridge.biz.BCartFunctionView;
import com.hd123.rumba.cartridge.entry.Entry;
import com.hd123.rumba.domain.CDomain;
import com.hd123.rumba.domain.IDomain;
import com.hd123.rumba.domain.IDomainMgr;
import com.hd123.rumba.exception.BusinessException;
import com.hd123.rumba.log.RumbaLogger;
import com.hd123.rumba.navigation.menu.BMenu;
import com.hd123.rumba.navigation.menu.BMenuItem;
import com.hd123.rumba.organization.COrganization;
import com.hd123.rumba.qt.QueryMgr;
import com.hd123.rumba.runtime.NamingMgr;
import com.hd123.rumba.runtime.OperateContext;
import com.hd123.rumba.runtime.backprocess.BackProcess;
import com.hd123.rumba.runtime.backprocess.Progress;
import com.hd123.rumba.user.CRole;
import com.hd123.rumba.user.CUser;
import com.hd123.rumba.user.IPermissionMgr;
import com.hd123.rumba.user.IRole;
import com.hd123.rumba.user.IRoleMgr;
import com.hd123.rumba.user.IUser;
import com.hd123.rumba.user.IUserMgr;

/**
 * 功能视图：高级系统管理
 * <p>
 * 
 * 标题：高级系统管理<br>
 * 前缀：RBAS<br>
 * 抽象：否<br>
 * 说明：提供根域用户（实施工程师）关于组织、域、以及用户认证与授权等系统维护功能的操作界面。<br>
 * 依赖：FVRumbaSystemCommon<br>
 * 
 * @author lxm
 * 
 */
public class FVRumbaAdvSys extends BCartFunctionView {

  public static final String FUNCV_PREFIX = "RBAS";

  @Override
  public boolean canLoadToDomain(IDomain domain) throws BusinessException, HibernateException {
    return CDomain.VALUE_ID_ROOT.equals(domain.getCode());
  }

  @Override
  public void onLoadToDomain(IDomain domain, IUser operator) throws BusinessException,
      HibernateException, InterruptedException {
    this.checkParameterNotNull(domain, "domain");
    this.checkParameterNotNull(operator, "operator");

    logger.setOperator(operator);
    progress = BackProcess.getProgress();
    progress.setMaxValue(2);

    createRolesT();
    progress.stepBy(1);
    createUsersT();
    progress.stepBy(1);
  }

  @Override
  public void onUnloadFromDomain(IDomain domain, IUser operator) throws BusinessException,
      HibernateException, InterruptedException {
    // Do Nothing
  }

  public static final String ID_ENTRY_ORGANIZATION = "organization";
  public static final String ID_ENTRY_DOMAIN = "domain";
  public static final String ID_ENTRY_CARTRIDGE = "cartridge";
  public static final String ID_ENTRY_USER = "user";
  public static final String ID_ENTRY_ROLE = "role";

  @Override
  protected void buildEntries() throws BusinessException {
    this.getEntries().clear();
    Entry e = null;

    e = this.appendEntry(ID_ENTRY_ORGANIZATION, COrganization.CAPTION_CLASS);
    e.setPermission(ViewOrganizationAdvSys.PERMISSION_VIEW);
    e.setImage("rumba/images/organization/org_small.gif");
    e.appendLink("organization/ViewOrganizationAdvSys?start=list");

    e = this.appendEntry(ID_ENTRY_DOMAIN, CDomain.CAPTION_CLASS);
    e.setPermission(ViewDomainAdvSys.PERMISSION_VIEW);
    e.setImage("rumba/images/domain/domain_small.gif");
    e.appendLink("domain/ViewDomainAdvSys?start=list");

    e = this.appendEntry(ID_ENTRY_CARTRIDGE, CCartridge.CAPTION_CLASS);
    e.setPermission(ViewCartridgeAdvSys.PERMISSION_CARTRIDGE_VIEW);
    e.setImage("rumba/images/cartridge/cartridge_small.gif");
    e.appendLink("cartridge/ViewCartridgeAdvSys?start=list");

    e = this.appendEntry(ID_ENTRY_USER, CUser.CAPTION_CLASS);
    e.setPermission(ViewUserAdvSys.PERMISSION_VIEW);
    e.setImage("rumba/images/user/user_small.gif");
    e.appendLink("user/ViewUserAdvSys?start=list");

    e = this.appendEntry(ID_ENTRY_ROLE, CRole.CAPTION_CLASS);
    e.setPermission(ViewRoleAdvSys.PERMISSION_VIEW);
    e.setImage("rumba/images/user/role_small.gif");
    e.appendLink("user/ViewRoleAdvSys?start=list");
  }

  @Override
  protected void buildMainMenu(BMenu mainMenu) throws BusinessException {
    BMenuItem miSystem = BMenuItem.build(null, "系统", null);
    mainMenu.addItem(miSystem, null);

    BMenuItem miOrgDomain = BMenuItem.build(null, COrganization.CAPTION_CLASS + "与"
        + CDomain.CAPTION_CLASS, null);
    miOrgDomain.setImage("rumba/images/organization/org_small.gif");
    mainMenu.addItem(miOrgDomain, miSystem);
    mainMenu.addItem(BMenuItem.build(this.getEntryById(ID_ENTRY_ORGANIZATION)), miOrgDomain);
    mainMenu.addItem(BMenuItem.build(this.getEntryById(ID_ENTRY_DOMAIN)), miOrgDomain);
    mainMenu.addItem(BMenuItem.build(this.getEntryById(ID_ENTRY_CARTRIDGE)), miOrgDomain);

    BMenuItem miUserMgr = BMenuItem.build(null, CUser.CAPTION_CLASS + "管理", null);
    miUserMgr.setImage("rumba/images/user/user_small.gif");
    mainMenu.addItem(miUserMgr, miSystem);
    mainMenu.addItem(BMenuItem.build(this.getEntryById(ID_ENTRY_USER)), miUserMgr);
    mainMenu.addItem(BMenuItem.build(this.getEntryById(ID_ENTRY_ROLE)), miUserMgr);

    BMenuItem miLogMgr = BMenuItem.build(null, "日志管理", null);
    mainMenu.addItem(miLogMgr, miSystem);
    mainMenu.addItem(BMenuItem.build(this.getEntryById(FVRumbaSystemCommon.class,
        FVRumbaSystemCommon.ID_ENTRY_LOG)), miLogMgr);
//
//    Entry eWeb = this.getEntryById(FVRumbaSystemCommon.class,
//        FVRumbaSystemCommon.ID_ENTRY_HEADINGWWW);
//    mainMenu.addItem(BMenuItem.build(eWeb, null, CMenuItem.VALUE_ALIGN_RIGHTBOTTOM), null);
  }

  private RumbaLogger logger = RumbaLogger.getLogger(this.getClass());
  private Progress progress = null;
  private IDomainMgr domainMgr = null;
  private IRoleMgr roleMgr = null;
  private IUserMgr userMgr = null;
  private IPermissionMgr permMgr = null;

  private IDomainMgr getDomainMgr() throws BusinessException {
    if (domainMgr == null)
      domainMgr = (IDomainMgr) NamingMgr.getInstance().lookupMgr(IDomainMgr.class);
    return domainMgr;
  }

  private IRoleMgr getRoleMgr() throws BusinessException {
    if (roleMgr == null)
      roleMgr = (IRoleMgr) NamingMgr.getInstance().lookupMgr(IRoleMgr.class);
    return roleMgr;
  }

  private IUserMgr getUserMgr() throws BusinessException {
    if (userMgr == null)
      userMgr = (IUserMgr) NamingMgr.getInstance().lookupMgr(IUserMgr.class);
    return userMgr;
  }

  private IPermissionMgr getPermMgr() throws BusinessException {
    if (permMgr == null)
      permMgr = (IPermissionMgr) NamingMgr.getInstance().lookupMgr(IPermissionMgr.class);
    return permMgr;
  }

  private void createRolesT() throws BusinessException, HibernateException {
    IDomain root = getDomainMgr().getRootDomain();
    OperateContext operate = new OperateContext(getUserMgr().getSysUser());
    String roleStr = CRole.CAPTION_CLASS + "\"" + CRole.VALUE_CODE_ROOT_ADMIN + "\"";

    try {
      logger.info("创建/更新" + roleStr + "，授予权限……");
      IRole role = doSaveRoleT(root, CRole.VALUE_CODE_ROOT_ADMIN, CRole.VALUE_NAME_ROOT_ADMIN,
          operate);

      // getPermMgr().addPermissionsForRoleT(role, Department.class);
      getPermMgr().addPermissionsForRoleT(role, CUser.class);
      getPermMgr().addPermissionsForRoleT(role, CDomain.class);
      getPermMgr().addPermissionsForRoleT(role, COrganization.class);
      // getPermMgr().addPermissionsForRoleT(role, Indicator.class);
      // getPermMgr().addPermissionsForRoleT(role, ImpexLog.class);
      getPermMgr().addPermissionsForRoleT(role, QueryMgr.class);

      getPermMgr().addPermissionsForRoleT(role, ViewOrganizationAdvSys.class);
      getPermMgr().addPermissionsForRoleT(role, ViewOrganizationSystem.class);
      getPermMgr().addPermissionsForRoleT(role, ViewDomainAdvSys.class);
      getPermMgr().addPermissionsForRoleT(role, ViewDomainSystem.class);
      getPermMgr().addPermissionsForRoleT(role, ViewCartridgeAdvSys.class);
      getPermMgr().addPermissionsForRoleT(role, ViewCartridgeSystem.class);
      getPermMgr().addPermissionsForRoleT(role, ViewRoleAdvSys.class);
      getPermMgr().addPermissionsForRoleT(role, ViewRoleSystem.class);
      getPermMgr().addPermissionsForRoleT(role, ViewUserAdvSys.class);
      getPermMgr().addPermissionsForRoleT(role, ViewUserSystem.class);
      getPermMgr().addPermissionsForRoleT(role, ViewActionLog.class);
    } catch (Exception e) {
      logger.error("创建/更新" + roleStr + "时发生错误。");
      if (e instanceof HibernateException)
        throw (HibernateException) e;
      else
        throw new BusinessException(e);
    }
  }

  private void createUsersT() throws BusinessException, HibernateException {
    IDomain root = getDomainMgr().getRootDomain();
    OperateContext operate = new OperateContext(getUserMgr().getSysUser());
    String userStr = CUser.CAPTION_CLASS + "\"" + CUser.VALUE_LOGIN_ROOT_ADMIN + "\"";
    String roleStr = CRole.CAPTION_CLASS + "\"" + CRole.VALUE_CODE_ROOT_ADMIN + "\"";

    try {
      logger.info("创建/更新" + userStr + "，授予" + roleStr + "……");
      IUser user = doSaveUserT(root, CUser.VALUE_LOGIN_ROOT_ADMIN, CUser.VALUE_PASSWORD_ROOT_ADMIN,
          CUser.VALUE_NAME_ROOT_ADMIN, operate);
      doAddRoleToUserT(root, user, CRole.VALUE_CODE_ROOT_ADMIN, operate);
    } catch (Exception e) {
      logger.error("创建/更新" + userStr + "时发生错误。");
      if (e instanceof HibernateException)
        throw (HibernateException) e;
      else
        throw new BusinessException(e);
    }
  }

  private IRole doSaveRoleT(IDomain domain, String roleCode, String roleName, OperateContext operate)
      throws BusinessException, HibernateException {
    IRole role = null;
    Transaction tx = getSession().beginTransaction();
    try {
      role = getRoleMgr().getRoleByCode(domain, roleCode);
      if (role == null)
        role = getRoleMgr().createRole(domain, roleCode, roleName);
      getRoleMgr().saveRole(role, operate);
      tx.commit();
    } catch (Exception e) {
      tx.rollback();
      if (e instanceof HibernateException)
        throw (HibernateException) e;
      else
        throw new BusinessException(e);
    } finally {
      getSession().flush();
    }
    return role;
  }

  private IUser doSaveUserT(IDomain domain, String userCode, String userPwd, String userName,
      OperateContext operate) throws BusinessException, HibernateException {
    IUser user = null;
    Transaction tx = getSession().beginTransaction();
    try {
      user = getUserMgr().getUserByLogin(domain, userCode);
      if (user == null)
        user = getUserMgr().createUser(domain, userCode);
      user.setName(userName);
      user.encodePassword(userPwd);
      user.setOnline(Boolean.TRUE);
      getUserMgr().saveUser(user, operate);
      tx.commit();
    } catch (Exception e) {
      tx.rollback();
      if (e instanceof HibernateException)
        throw (HibernateException) e;
      else
        throw new BusinessException(e);
    } finally {
      getSession().flush();
    }
    return user;
  }

  private void doAddRoleToUserT(IDomain domain, IUser user, String roleCode, OperateContext operate)
      throws BusinessException, HibernateException {
    Transaction tx = getSession().beginTransaction();
    try {
      IRole role = getRoleMgr().getRoleByCode(domain, roleCode);
      if (role != null)
        getUserMgr().assignRoleToUser(role, user, operate);
      tx.commit();
    } catch (Exception e) {
      tx.rollback();
      if (e instanceof HibernateException)
        throw (HibernateException) e;
      else
        throw new BusinessException(e);
    } finally {
      getSession().flush();
    }
  }

}
